export default class WebSocketService {
    constructor(userId) {
        this.userId = userId;
        this.socket = null;
        this.url = `ws://localhost:8080/pushMessage/${this.userId}`;
        this.connect();
    }

    connect() {
        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            console.log('WebSocket connection established');
        };

        this.socket.onmessage = (event) => {
            this.handleMessage(event.data);
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket Error:', error);
        };

        this.socket.onclose = () => {
            console.log('WebSocket connection closed');
            this.reconnect();
        };
    }
    // 发送消息
    sendMessage(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.error('WebSocket is not connected');
        }
    }

    // 处理接收到的消息
    handleMessage(message) {
        console.log('Received message:', message);
    }

    // 尝试重新连接
    reconnect() {
        console.log('Attempting to reconnect...');
        setTimeout(() => {
            this.connect();
        }, 5000);
    }

    // 关闭 WebSocket 连接
    close() {
        if (this.socket) {
            this.socket.close();
            console.log('WebSocket connection closed manually');
        }
    }
}